package com.gopay.common.util;

import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MD5Util {
    /** Logger for logging information. */
    private static Log log = LogFactory.getLog("MD5Util");

    /**
     * MD加密
     * 
     * @param src
     *            明文
     * @return 密文
     */
    public static final String sign(String src) {
        final int i4 = 4;
        final int i0xf = 0xf;
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = src.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            /* 转换为16进制 */
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> i4 & i0xf];
                str[k++] = hexDigits[byte0 & i0xf];
            }
            return new String(str);
        } catch (Exception e) {
            log.error("MD5加密错误", e);
            return null;
        }
    }

    /**
     * MD加密
     * 
     * @param src
     *            明文
     * @param type
     *            编码格式
     * @return 密文
     */
    public static final String signType(String src, String type) {
        final int i4 = 4;
        final int i0xf = 0xf;
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = src.getBytes(type);
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            /* 转换为16进制 */
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> i4 & i0xf];
                str[k++] = hexDigits[byte0 & i0xf];
            }
            return new String(str);
        } catch (Exception e) {
            log.error("MD5加密错误", e);
            return null;
        }
    }
}
